package api

import (
	"context"
	"google.golang.org/grpc"
	"learning-pass/common/proto/user"
)

type Handler func(ctx context.Context, client user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8082", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func Register(ctx context.Context, i *user.RegisterReq) (*user.RegisterResp, error) {
	userClient, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		register, err := in.Register(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return userClient.(*user.RegisterResp), nil
}
func Login(ctx context.Context, i *user.LoginReq) (*user.LoginResp, error) {
	userClient, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.Login(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return userClient.(*user.LoginResp), nil
}
func AddUserStudyPlan(ctx context.Context, i *user.AddUserStudyPlanReq) (*user.AddUserStudyPlanResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		plan, err := in.AddUserStudyPlan(ctx, i)
		if err != nil {
			return nil, err
		}
		return plan, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.AddUserStudyPlanResp), nil
}
func DelUserStudyPlan(ctx context.Context, i *user.DelUserStudyPlanReq) (*user.DelUserStudyPlanResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		plan, err := in.DelUserStudyPlan(ctx, i)
		if err != nil {
			return nil, err
		}
		return plan, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.DelUserStudyPlanResp), nil
}
